<template>
	<view class="main-content">
		<MHeader>{{state.pageName}}</MHeader>
		<scroll-view scroll-y="true" style="height:calc(100% - 180rpx)">
			<!-- 业务经理 -->
			<view>
				<item name="养殖批次" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_BREEDBATCHName"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataOne','F_QUQY_BREEDBATCH','FNUMBER','F_QUQY_BREEDBATCHName','FNumber','FName')" />
				</item>
				<item name="组织" sign must>
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName" disabled placeholder="请选择" @click.native="choose('ORG_Organizations','F_QUQY_ORGID','FNumber','F_QUQY_ORGName','FNumber','FName')" /> -->
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName" disabled placeholder="自动带出" />
				</item>
				<item name="养殖批次编码" must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_BREEDBATCH.FNUMBER" disabled placeholder="自动带出" />
				</item>
				<item name="日期" must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_DATE"  @click="chooseT('F_QUQY_DATE')" placeholder="请选择" />
				</item>
				<item name="目前在栏数量">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_COLUMNQTY" type="number" style="padding-right: 35rpx;" disabled placeholder="自动带出" />
					<text class="symbol">只</text>
				</item>
				<item name="损失数量">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_QTY" type="number" style="padding-right: 35rpx;" />
					<text class="symbol">只</text>
				</item>
				<item name="备注">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_REMARK" placeholder="请输入" />
				</item>
			</view>
			<view>
				<UpLoad ref="upload" @remove="remove" :disabled="state.myInfo.role.includes(7)"></UpLoad>
			</view>
		</scroll-view>
		<view class="btns">
			<van-button type="primary" size="small" @click="save">保 存</van-button>
		</view>
	</view>
	<ChooseTime ref="chooseTime" />
	<Loading v-if="state.loading" />
</template>

<script setup>
	// 技术员：保存 提交 撤销
	// QUQY_LossInfoMiao
	import moment from 'moment'
	import { reactive, getCurrentInstance, ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { checkForm, msg } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		loading: true,
		info: {
			FormId: 'QUQY_LossInfoMiao',
			Data: {
				Model: {
					F_QUQY_ORGID: {
						FNumber: null
					},
					F_QUQY_BREEDBATCH: {
						FNUMBER: null
					},
					F_QUQY_FJID: ''
				}
			}
		},
		rules: {
			F_QUQY_ORGID: '请选择组织！',
			F_QUQY_BREEDBATCHName: '请选择养殖批次！',
			F_QUQY_DATE: '请选择日期！'
		},
		pageName: "苗损申请",
		myInfo: null
	})

	const chooseTime = ref(null)
	const chooseT = (fieldName) => {
		chooseTime.value.start(state.info.Data.Model, fieldName)
	}

	// 1.组织控制（使用组织为当前选择的组织）：养殖批次
	const choose = (FormId, Field, FieldSon, FieldName, IdKey, IdKeyName, Group, BringOther) => {
		// 🐟 选择组织前
		if (Field == 'F_QUQY_ORGID') {

		}

		// 🐟 1
		let mustHasOrg = []
		if (mustHasOrg.includes(Field)) {
			if (!state.info.Data.Model.F_QUQY_ORGName) return msg('请先选择组织！')
		}
		
		let url = `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择&R=`
		let myRole = state.myInfo.role.join(',')
		url = url + myRole
		uni.navigateTo({
			url: url,
			success: res => { res.eventChannel.emit('fun', [fun]) }
		})

		// 回调方法
		let fun = (list) => {
			state.info.Data.Model[Field][FieldSon] = list[0][IdKey]
			state.info.Data.Model[FieldName] = list[0][IdKeyName]
			if (BringOther) {
				state.info.Data.Model[BringOther[0]] = list[0][BringOther[1]]
			}

			// 🐟 选择组织后
			if (Field == 'F_QUQY_ORGID') {

				// 🍕 初始化 养殖批次等字段及其带出的字段
				for (let key in state.info.Data.Model) {
					let value = state.info.Data.Model[key]
					if (mustHasOrg.includes(key) && value) {
						if (typeof(value) === 'object') {
							for (let k in value) { value[k] = null }
							state.info.Data.Model[`${key}Name`] = null
							if (state.info.Data.Model[`${key}TEM`]) state.info.Data.Model[`${key}TEM`] = null // 带出的字段
						} else {
							value = null
						}
					}
				}
				// 🍕 初始化在栏数量
				state.info.Data.Model.F_QUQY_COLUMNQTY = null
			}

			// 🐟 选择养殖批次
			if (Field == 'F_QUQY_BREEDBATCH') {
				// 🍕 在栏数量
				state.info.Data.Model.F_QUQY_COLUMNQTY = list[0].F_QUQY_COLUMNQTY
				// 🍕 组织
				state.info.Data.Model.F_QUQY_ORGID = {
					FNumber: list[0]['FUseOrgId.FNumber']
				}
				state.info.Data.Model.F_QUQY_ORGName = list[0]['FUseOrgId.FName']
			}
		}
	}

	const getDetails = (Id) => {
		kdApis.formView({
			formId: 'QUQY_LossInfoMiao',
			data: { Id }
		}).then(res => {
			if (res) {
				// 🍕 业务员部分
				let obj = {
					// BillNo: res.BillNo,
					FId: res.Id,
					F_QUQY_ORGID: {
						FNumber: res.F_QUQY_ORGID?.Number
					},
					F_QUQY_ORGName: res.F_QUQY_ORGID?.Name[0].Value,
					F_QUQY_BREEDBATCH: {
						FNUMBER: res.F_QUQY_BREEDBATCH?.Number
					},
					F_QUQY_BREEDBATCHName: res.F_QUQY_BREEDBATCH?.Name[0].Value,
					F_QUQY_DATE: moment(res.F_QUQY_DATE).format('YYYY-MM-DD'),
					F_QUQY_COLUMNQTY: res.F_QUQY_COLUMNQTY,
					F_QUQY_QTY: res.F_QUQY_QTY,
					F_QUQY_AMOUNT: res.F_QUQY_AMOUNT,
					F_QUQY_REMARK: res.F_QUQY_REMARK,
					F_QUQY_FJID: res.F_QUQY_FJID
				}

				Object.assign(state.info.Data.Model, obj)
				getFiles(Id)
				state.loading = false
			}
		})
	}


	const save = async (FId) => {
		await checkForm(state.info.Data.Model, state.rules)
		if (FId) {
			// 保存附件后
			state.info.Data.Model.FId = FId
		} else {
			// 保存 如果是编辑保存
			if (state.info.Data.Model.FId) return upLoadFile({ InterId: state.info.Data.Model.FId, BillNO: state.info.Data.Model.BillNo })
		}
		kdApis.formSave(state.info).then(res => {
			if (res) {
				if (!FId) {
					upLoadFile({ InterId: res.Result.Id, BillNO: res.Result.Number })
				} else {
					msg('保存成功！')
					setTimeout(() => {
						uni.navigateBack()
					}, 300)
				}
			}
		})
	}
	
	
	const upload = ref(null)
	
	const upLoadFile = async ({ InterId, BillNO }) => {
		if (upload.value.data.reUp) {
			let Ids = state.info.Data.Model.F_QUQY_FJID.split(',').filter(it => it.trim())
			let requests = []
			upload.value.data.fileList.forEach(it => {
				it.FormId = 'QUQY_SeedPlan'
				it.InterId = InterId
				it.BillNO = BillNO
				if (!it.Id) requests.push(kdApis.fileUpLoad({ data: it }))
			})
			let x = await axios.all(requests).then(res => {
				if (res) {
					Ids = res.filter(it => it.Result.ResponseStatus.SuccessEntitys[0]).map(it => it.Result.ResponseStatus.SuccessEntitys[0].Id).concat(Ids)
				}
			})
	
			let obj = upload.value.data.fileListLarge
			if (Object.keys(obj).length !== 0) {
				for (let key in obj) {
					let value = obj[key] // Array
					let result = await kdApis.fileUpLoad({ data: { ...value[0], FormId: 'QUQY_SeedPlan', InterId, BillNO } })
					for (let [i, val] of value.entries()) {
						if (i) {
							let resu = await kdApis.fileUpLoad({ data: { ...val, FormId: 'QUQY_SeedPlan', InterId, BillNO, FileId: result.Result.FileId } })
							if (resu && resu.Result.ResponseStatus.SuccessEntitys[0]) {
								Ids.push(resu.Result.ResponseStatus.SuccessEntitys[0].Id)
							}
						}
					}
				}
			}
	
			state.info.Data.Model.F_QUQY_FJID = Ids.join(',')
			save(InterId)
		} else {
			msg('保存成功！')
			save(InterId)
		}
	}
	
	const remove = (Id) => {
		if (state.info.Data.Model.F_QUQY_FJID) {
			let arr = state.info.Data.Model.F_QUQY_FJID.split(',')
			let index = arr.indexOf(Id)
			if (index > -1) arr.splice(index, 1)
			state.info.Data.Model.F_QUQY_FJID = arr.join(',')
		}
	}
	
	function mergeUint8Arrays(arrays) {
		const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
		const mergedArray = new Uint8Array(totalLength);
		let offset = 0;
	
		for (const arr of arrays) {
			mergedArray.set(arr, offset);
			offset += arr.length;
		}
		return mergedArray;
	}
	
	const getFile = async (res, str, FileId, StartIndex, fun) => {
		if (res.Result.IsLast == true) {
			fun(str)
		} else {
			let result = await kdApis.fileDownLoad({ data: { FileId: FileId, StartIndex } })
			if (result) {
				let Uint8Array = base64ToUint8Array(result.Result.FilePart)
				let mx = mergeUint8Arrays([str, Uint8Array])
				getFile(result, mx, FileId, result.Result.StartIndex, fun)
			}
		}
	}
	
	const getFiles = async (Id) => {
		let fjs = state.info.Data.Model.F_QUQY_FJID.split(',').filter(it => it.trim())
		if (fjs.length == 0) return
		let files = []
		let files2 = []
		for (let it of fjs) {
			let fileInfo = await kdApis.formView({ formId: 'BOS_Attachment', data: { Id: it } })
			if (fileInfo) {
				let fileDetais = await kdApis.fileDownLoad({ data: { FileId: fileInfo.FileId, StartIndex: 0 } })
				if (fileDetais) {
					if (fileDetais.Result.IsLast == false) {
						let fun = (val) => {
							var blob = new Blob([val], { type: `image/${fileInfo.ExtName.slice(1)}` })
							let src = URL.createObjectURL(blob)
							files.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
							files2.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
						}
						getFile(fileDetais, base64ToUint8Array(fileDetais.Result.FilePart), fileInfo.FileId, fileDetais.Result.StartIndex, fun)
					} else {
						let Uint8Array = base64ToUint8Array(fileDetais.Result.FilePart)
						var blob = new Blob([Uint8Array], { type: `image/${fileInfo.ExtName.slice(1)}` })
						let src = URL.createObjectURL(blob)
						files.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
						files2.push({ path: src, FileId: fileInfo.FileId, Id: it, FieldName: fileDetais.Result.FileName })
					}
				}
	
			}
		}
		upload.value.data.fileList2 = files2
		upload.value.data.fileList = files
	}
	

	onLoad(async (query) => {
		state.myInfo = uni.getStorageSync('myInfo')
		if (query.Id) {
			state.pageName = "苗损编辑"
			getDetails(query.Id)
		} else {
			// 🍕 日期默认当前日期
			state.info.Data.Model.F_QUQY_DATE = moment(new Date()).format('YYYY-MM-DD')
			state.loading = false
		}
	})
</script>
<style lang="scss" scoped>

</style>